package com.chuanqi.shop.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chuanqi.shop.domain.Template;
import com.chuanqi.shop.service.TemplateService;

@Controller
@RequestMapping(path="/shop/template")
public class TemplateController {
	@Autowired
	private TemplateService templateService;
	
	@RequestMapping(path="/get/{id}", method=RequestMethod.GET)
	public String getTemplate(@PathVariable("id") Long id, Model model){		
		Template template = templateService.getById(id);
		System.out.println(template.getId());
		System.out.println(template.getNavigation());
		model.addAttribute("template", template);  				
		return "shop/template/template" + id;
	}
	
	@RequestMapping(path = "/update/{id}", method = RequestMethod.GET)
	public String updateGet(@PathVariable("id") Long id, Model model) {		
		Template template = templateService.getById(id);
		model.addAttribute("template", template);
		model.addAttribute("action", "update");
		return "shop/template/form";
	}
	
	@RequestMapping(path = "/update", method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("template") Template template, BindingResult result, RedirectAttributes redirectAttributes, Model model) {
		if (result.hasErrors()) {
			model.addAttribute("action", "update");
			return "shop/template/form";
		}
		if (template != null) {
			templateService.update(template);
			redirectAttributes.addFlashAttribute("message", "更新模版成功!");
		}
		
		return "redirect:/shop/template/list";
	}	
}
